public class Solution {
    public int countDigitOne(int n) {
        return recur(n);
    }

    private int recur(int n) {
        if (n <= 0) return 0;
        String str = String.valueOf(n);
        int high = str.charAt(0) - '0';
        int pow = (int) Math.pow(10, str.length() - 1);
        int last = n - pow * high;
        int other = (int) (Math.pow(10, str.length() - 2) * (str.length() - 1) * high);
        if (high == 1) {
            return last + 1 + recur(last) + other;
        } else {
            return pow + recur(last) + other;
        }
    }
}
